package main

import "flag"
import "fmt"
import "strings"
import "shardmaster"
import "bufio"
import "os"
import "strconv"

var g_masters = flag.String("masters", "", "addresses of the master servers")

func main() {
	flag.Parse()
	masters := strings.Split(*g_masters, ",")
	ck := shardmaster.MakeClerk(masters)
	in := bufio.NewReader(os.Stdin)
	for {
		fmt.Printf(">>>")
		line, err := in.ReadString('\n')
		if err != nil {
			fmt.Printf("Error in reading input: %v\n", err)
			break
		}
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "join") {
			terms := strings.Split(line, " ")
			if len(terms) != 3 {
				fmt.Printf("Format error. Usage: join GID SERVERS\n")
				continue
			}
			gid, err := strconv.ParseInt(terms[1], 0, 64)
			if err != nil {
				fmt.Printf("Error in parsing GID: %v\n", err)
				continue
			}
			group := strings.Split(terms[2], ",")
			ck.Join(gid, group)
			fmt.Println("OK")
		} else if strings.HasPrefix(line, "query") {
			cfg := ck.Query(-1)
			fmt.Printf("%v\n", cfg)
		} else if strings.HasPrefix(line, "leave") {
			terms := strings.Split(line, " ")
			if len(terms) != 2 {
				fmt.Printf("Format error. Usage: leave GID\n")
				continue
			}
			gid, err := strconv.ParseInt(terms[1], 0, 64)
			if err != nil {
				fmt.Printf("Error in parsing GID: %v\n", err)
				continue
			}
			ck.Leave(gid)
			fmt.Println("OK")
		} else if strings.HasPrefix(line, "quit") {
			fmt.Println("Bye")
			break
		}
	}

}
